/*
 ============================================================================
 Name		: RecognitionManager.cpp
 Author	  : Lenka Litvova
 Version	 : 1.0
 Copyright   : Your copyright notice
 Description : CRecognitionManager implementation
 ============================================================================
 */

#include "RecognitionManager.h"
#include "UserDatabase.h"
#include "FRamI_UIAppUi.h"

CRecognitionManager::CRecognitionManager(CFRamI_UIAppUi *aAppUi):iAppUi(aAppUi)
	{
	// No implementation required
	}

CRecognitionManager::~CRecognitionManager()
	{
		if(iRecognizer)
			delete iRecognizer;
		if(iAuthetificator)
			delete iAuthetificator;
	}

CRecognitionManager* CRecognitionManager::NewLC(CFRamI_UIAppUi *aAppUi)
	{
	CRecognitionManager* self = new (ELeave) CRecognitionManager(aAppUi);
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

CRecognitionManager* CRecognitionManager::NewL(CFRamI_UIAppUi *aAppUi)
	{
	CRecognitionManager* self = CRecognitionManager::NewLC(aAppUi);
	CleanupStack::Pop(); // self;
	return self;
	}

void CRecognitionManager::ConstructL()
	{
	}

void CRecognitionManager::RecognizeAuthorized(CNokiaCVImage *aImage, TDesC& aUsername)
	{
		iAuthetificationMode = EFalse;
		iUserTested = &aUsername;
		if(iRecognizer)
			delete iRecognizer;
		iRecognizer = CFaceRecognizer::NewL(aImage, this);
		iRecognizer->StartL();
	}

void CRecognitionManager::Authetificate(CNokiaCVImage *aImage)
	{
		iAuthetificationMode = ETrue;
		if(iRecognizer)
			delete iRecognizer;
		iRecognizer = CFaceRecognizer::NewL(aImage, this);
		iRecognizer->StartL();
	}

void CRecognitionManager::RecognitionFinishedL(MRecognitionObserver::TRecognitionState aState)
	{
		if(aState == MRecognitionObserver::EFaceRecognized)
		{
			//z obrazku bol vyextrahovany graf
			CFaceGraph *face = iRecognizer->GetGraph();
			
			if(iAuthetificationMode)
			{
				if(iAuthetificator)
					delete iAuthetificator;
				iAuthetificator = CFaceAuthetificator::NewL(face, this);
				iAuthetificator->StartL();
			}
			else
			{
				TBool result = CUserDatabase::AddNewAuthorizedUser(face, *iUserTested);
				if(result)
					iAppUi->UserAdded(ETrue);
				else
					iAppUi->UserAdded(-1);
			}
		}
		else
		{
			if(iAuthetificationMode)
			{
			iAppUi->UserAuthetificated(EFalse);
			}
			else
			{
			iAppUi->UserAdded(EFalse);
			}
		}
	}

void CRecognitionManager::AuthetificationFinishedL(TBool aResult)
	{
	iAppUi->UserAuthetificated(aResult);
	}
